<template>
  <!-- 添加员工弹窗 -->
  <el-dialog title="新增员工" :visible="showDialog" @close="btnCancel">
    <!-- 表单 -->
    <el-form ref="roleForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="formData.username" style="width:90%" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="formData.mobile" style="width:90%" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker v-model="formData.timeOfEntry" style="width:90%" placeholder="请选择入职时间" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="formData.formOfEmployment" style="width:90%" placeholder="请选择">
          <!-- 遍历枚举中的聘用形式,给用户看得标签就是聘用形式值,绑定的值就是id -->
          <el-option v-for="item in employeeEnum.hireType" :key="item.id" :label="item.value" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="formData.workNumber" style="width:90%" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <!-- 获取焦点下拉显示树形数据 -->
        <el-input
          v-model="formData.departmentName"
          style="width:90%"
          placeholder="请选择部门"
          @focus="getDeptsTree"
          @blur="treeHide"
        />
        <!-- 放置一个树形组件 -->
        <!-- node就是当前节点,点击当前节点执行事件 -->
        <el-tree
          v-if="treeShow"
          :data="treeData"
          default-expand-all
          :props="{label:'name'}"
          @node-click="selectNode"
        />
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker v-model="formData.correctionTime" style="width:90%" placeholder="请选择转正时间" />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
// 新增员工接口
import { addEmployee } from '@/api/employee'
// 获取部门数据
import { getDepartments } from '@/api/departments'
// 树形转换函数
import { listToTreeData } from '@/utils/index'
// 引入枚举
import employeeEnum from '@/api/constant/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },

  data() {
    // 校验工号
    const checkWorkNumber = (rule, val, callback) => {
      // 如果用户输入了值,校验是否含有中文
      if (val) {
        if (/[\u4E00-\u9FA5]/g.test(val)) {
          callback(new Error('输入的值不能含有中文'))
        } else {
          callback()
        }
      }
      callback()
    }
    // 校验入职时间
    const checkTimeOfEntry = (rule, val, callback) => {
      if (val && this.formData.correctionTime) {
        if (this.formData.correctionTime < val) {
          callback(new Error('入职时间不能比转正时间晚'))
        } else {
          callback()
        }
      }
      callback()
    }
    // 校验转正时间
    const checkCorrectionTime = (rule, val, callback) => {
      if (val && this.formData.timeOfEntry) {
        // console.log(val)
        // console.log(this.formData.timeOfEntry)
        if (this.formData.timeOfEntry > val) {
          callback(new Error('转正时间不能比入职时间早'))
        } else {
          callback()
        }
      }
      callback()
    }

    return {
      employeeEnum, // 引入的枚举数据
      treeData: [], // 接收转换后的树形数据
      treeShow: false, // 控制树形数据显示隐藏
      formData: {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      rules: {
        username: [
          { required: true, message: '名字不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度为1-6个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '聘用形式不能为空', trigger: ['blur', 'change'] }
        ],
        workNumber: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          { validator: checkWorkNumber, trigger: 'blur' }
        ],
        departmentName: [{ required: true, message: '部门不能为空', trigger: ['blur', 'change'] }],
        timeOfEntry: [
          { required: true, message: '入职时间不能为空', trigger: 'blur' },
          { validator: checkTimeOfEntry, trigger: 'blur' }
        ],
        correctionTime: [
          { required: true, message: '转正时间不能为空', trigger: 'blur' },
          { validator: checkCorrectionTime, trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 获取部门数据,转换为树形数据
    async getDeptsTree() {
      // 解构出depts
      const { depts } = await getDepartments()
      // 将depts转换为树形数据
      this.treeData = listToTreeData(depts, '')
      // console.log(this.treeData)
      // 显示树形
      this.treeShow = true
    },

    // 选择node节点,将节点的值传入departmentName
    selectNode(node) {
      // console.log(node)
      this.formData.departmentName = node.name
      this.treeShow = false
    },

    // 部门input失焦隐藏树形
    treeHide() {
      setTimeout(() => {
        this.treeShow = false
      }, 100)
    },

    // 点击确定
    async btnOK() {
      try {
        // 校验
        await this.$refs.roleForm.validate()
        // 发请求
        await addEmployee(this.formData)
        this.$message.success('新增员工成功')
        // 通知父组件更新员工列表,$parent可以直接调用父组件实例,其实就是父组件的this
        this.$parent.getEmployeeList()
        this.$parent.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },

    // 点击取消
    btnCancel() {
      // 通知父组件关闭弹窗
      this.$emit('update:showDialog', false)
      // 清除表单数据
      this.formData = {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      }
      this.$refs.roleForm.resetFields() // 重置校验结果
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-tree{
    z-index: 9;
    border: #2bc6e283 solid 1px;
    height: 200px;
    overflow: auto;
    width: 90%;
    border-radius: 5px;
  }
</style>
